﻿using MahApps.Metro.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace LunarSF.SHomeWorkshop.LunarMarkdownEditor
{
    /// <summary>
    /// OptionBox.xaml 的交互逻辑
    /// </summary>
    public partial class OptionBox : MetroWindow
    {
        public OptionBox()
        {
            InitializeComponent();
            this.Loaded += OptionBox_Loaded;
        }

        private void OptionBox_Loaded(object sender, RoutedEventArgs e)
        {
            switch (this.OptionType)
            {
                case Type.ListBox:
                    if (listBox != null)
                        listBox.Focus();
                    break;
            }
        }

        /// <summary>
        /// 选项以何种样式呈现。
        /// </summary>
        public enum Type { RadioButtons, ListBox }

        public Type OptionType { get; set; }

        private ListBox listBox = null;

        /// <summary>
        /// 显示一个输入框，并获取输入的数据。
        /// </summary>
        /// <param name="title">输入框标题。</param>
        /// <param name="prompt">输入框中的提示文本。</param>
        /// <param name="optionLines">用以生成选择项的字符串，各选择项应以“\n”字符分隔</param>
        /// <param name="defaultValue">输入框的默认文本。</param>
        /// <param name="prompt2">第二提示文本。</param>
        public static string Show(string title, string prompt, string optionLines, string defaultValue = "", string prompt2 = null, bool compelRadioButton = false)
        {
            if (string.IsNullOrWhiteSpace(optionLines))
            {
                MessageBox.Show("给 OptionBox.Show() 方法的 optionLines 参数传入的值无效！", Globals.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return "";
            }

            try
            {
                OptionBox obx = new OptionBox();
                obx.Owner = App.Current.MainWindow;
                obx.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                obx.Icon = obx.Owner.Icon;
                obx.Title = string.IsNullOrWhiteSpace(title) ? (Globals.AppName + " - 选择框") : title;
                obx.tbxPrompt.Text = prompt;

                // 根据 optionsLines 到底能拆分出多少行来决定是使用 RadioButton 组还是 ComboBox。
                // 如果有效行数少于等于6行，就使用 RadioButton，否则使用 ComboBox。
                var lines = optionLines.Split(new char[] { '\r', '\n', }, StringSplitOptions.RemoveEmptyEntries);

                if (lines.Length <= 10 || compelRadioButton)
                {
                    obx.OptionType = Type.RadioButtons;
                    // 以 Radio Button 样式呈现
                    var sp = new StackPanel();
                    ScrollViewer sc = new ScrollViewer()
                    {
                        Margin = new Thickness(10, 10, 10, 5),
                        HorizontalAlignment = HorizontalAlignment.Stretch,
                        VerticalAlignment = VerticalAlignment.Stretch,
                        HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,
                        VerticalScrollBarVisibility = ScrollBarVisibility.Visible,
                    };

                    sc.Content = sp;
                    Grid.SetColumnSpan(sc, 2);
                    Grid.SetRow(sc, 1);

                    foreach (var line in lines)
                    {
                        RadioButton rbtn = new RadioButton() { Content = line, Tag = obx, Margin = new Thickness(10, 5, 10, 5), };
                        if (line.Trim().ToLower() == defaultValue.Trim().ToLower())
                        {
                            obx.optionText = line;
                            rbtn.IsChecked = true;
                        }
                        rbtn.Tag = obx;
                        rbtn.Checked += Rbtn_Checked;
                        rbtn.MouseDoubleClick += Rbtn_MouseDoubleClick;
                        sp.Children.Add(rbtn);
                    }

                    obx.mainGrid.Children.Add(sc);
                }
                else
                {
                    obx.OptionType = Type.ListBox;
                    // 改用 ListBox 样式呈现
                    obx.listBox = new ListBox()
                    {
                        Margin = new Thickness(10, 10, 10, 5),
                        VerticalAlignment = VerticalAlignment.Stretch,
                        HorizontalAlignment = HorizontalAlignment.Stretch,
                    };
                    Grid.SetColumnSpan(obx.listBox, 2);
                    Grid.SetRow(obx.listBox, 1);

                    foreach (var line in lines)
                    {
                        var newItem = new ListBoxItem() { Content = line, Tag = obx, };
                        if (line.Trim().ToLower() == defaultValue.Trim().ToLower())
                        {
                            obx.optionText = line;
                            newItem.IsSelected = true;
                        }
                        obx.listBox.Items.Add(newItem);
                        newItem.MouseDoubleClick += NewItem_MouseDoubleClick;
                    }
                    obx.mainGrid.Children.Add(obx.listBox);
                    obx.listBox.SelectionChanged += ListBox_SelectionChanged;
                }

                if (string.IsNullOrEmpty(prompt2))
                {
                    obx.tbxPrompt2.Visibility = Visibility.Collapsed;
                }
                else
                {
                    obx.tbxPrompt2.Visibility = Visibility.Visible;
                    obx.tbxPrompt2.Text = prompt2;
                }

                if (obx.ShowDialog() == true)
                {
                    return obx.OptionText;//原文输出
                }

                return "";
            }
            catch (Exception ex)
            {
                LMessageBox.Show(ex.Message, Globals.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return "";
            }
        }

        private static void NewItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var lbi = sender as ListBoxItem;
            if (lbi == null) return;

            lbi.IsSelected = true;
            var obx = lbi.Tag as OptionBox;
            if (obx == null) return;

            obx.OK();
        }

        private static void Rbtn_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var rbtn = sender as RadioButton;
            if (rbtn == null) return;

            rbtn.IsChecked = true;
            var obx = rbtn.Tag as OptionBox;
            if (obx == null) return;

            obx.OK();
        }

        private static void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var combo = sender as ListBox;
            if (combo == null) return;

            var ci = combo.SelectedItem as ListBoxItem;
            if (ci == null) return;

            var obx = ci.Tag as OptionBox;
            if (obx == null) return;

            obx.optionText = ci.Content as string;
        }

        private static void Rbtn_Checked(object sender, RoutedEventArgs e)
        {
            var rbtn = (sender as RadioButton);
            if (rbtn == null) return;
            var obx = rbtn.Tag as OptionBox;
            if (obx != null) obx.optionText = rbtn.Content as string;
        }

        private string optionText = "";
        /// <summary>
        /// 
        /// </summary>
        public string OptionText
        {
            get { return optionText; }
        }

        /// <summary>
        /// 完成输入。
        /// </summary>
        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            OK();
        }

        public void OK()
        {
            this.DialogResult = true;
            this.Close();
        }

        /// <summary>
        /// 放弃输入，关闭窗口。
        /// </summary>
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            this.Close();
        }

    }
}
